<template>
  <div style="display: flex;  flex-direction: column;">
    <div style="display: flex; max-height: 300px; margin-left: 80px; margin-top: -15px">
      <div style="display: flex;  flex-direction: column; margin-left: 20px">
        <h5 style="margin-top: 15px">项目类型</h5>
      <el-table :data="projectTypeCount"  style="width: 120px; max-height: 180px; margin-top: 5px; margin-left: -10px">
        <el-table-column prop="projectType" label="项目类型" width="70">
          <template slot-scope="scope">
            <!-- 根据 projectType 的值动态显示内容 -->
            <span v-if="scope.row.projectType === '工程'">工程</span>
            <span v-else-if="scope.row.projectType === '耗材'">耗材</span>
            <span v-else-if="scope.row.projectType === '设备'">设备</span>
            <span v-else-if="scope.row.projectType === '维护'">维护</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="数量" width="50"></el-table-column>
      </el-table>
      </div>
      <div id="projectType" style="width: 360px; height: 250px;"></div>
      <div style="display: flex; flex-direction: column; margin-left: 138px;">
        <h5 style="margin-top: 15px">采购方式</h5>
        <el-table :data="procurementMethodCount"  style="width: 120px; max-height: 140px; margin-top: 10px; margin-left: -10px">
          <el-table-column prop="procurementMethod" label="采购方式" width="70">
            <template slot-scope="scope2">
              <!-- 根据 projectType 的值动态显示内容 -->
              <span v-if="scope2.row.procurementMethod === '磋商'">磋商</span>
              <span v-else-if="scope2.row.procurementMethod === '委托'">委托</span>
              <span v-else-if="scope2.row.procurementMethod === '竞价'">竞价</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" width="50"></el-table-column>
        </el-table>
      </div>
      <div id="procurementMethod" style="width: 360px; height: 250px;"></div>
    </div>
    <div style="margin-left: 80px; display: flex;">
      <div style="display: flex;  flex-direction: column; margin-left: 20px">
        <h5>科室项目</h5>
        <div id="sciproj" style="width: 300px; height: 200px; width: 450px; height: 250px; margin-top: -40px"></div>
      </div>
      <div style="display: flex;  flex-direction: column; margin-left: 160px">
        <h5>归档项目</h5>
        <div id="vertical-bar-chart" style="width: 300px; height: 200px; width: 360px; height: 250px; margin-top: -20px"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getPT, getSPBar, getPM,getProjectsBySStatus} from "@/api/project";

export default {
  name: 'MyChart',
  data() {
    return {
      projectTypeData:[],//项目类型表原始数据
      projectTypeCount:[],//项目类型表转换后数据
      procurementMethodData: [],
      procurementMethodCount: [],
      //饼图数据
      projectTypeDataPie: [], //项目类型饼图数据
      procurementMethodDataPie: [],

      chart: null,
      projectData: [],
      filteredData: [],
      years: [], // 存储从数据中提取的年份
    };
  },
  mounted() {
    this.projectType();//饼图1
    this.procurementMethod();//饼图2
    this.departmentProjects();
    this.archiveTheProject();
  },
  methods: {
    projectType() {
      const chartDom = document.getElementById('projectType');
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center',
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['60%', '0%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'inner', // 标签位置
              formatter: '{d}%' // 使用百分比
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.projectTypeDataPie  // 使用组件的数据来定义饼图数据
          }
        ]
      };
      getPT().then(res => {
        this.projectTypeData = res;
        this.projectTypeDataPie = res;
        // 将对象转换为数组并格式化为适合 el-table 的数据格式
        this.projectTypeCount = Object.entries(this.projectTypeData).map(([key, value]) => ({
          projectType: key,
          count: value
        }));

        option.series[0].data = [
          {name: "工程", value: res["工程"]},
          {name: "耗材", value: res["耗材"]},
          {name: "设备", value: res["设备"]},
          {name: "维护", value: res["维护"]},
        ]
        myChart.setOption(option);

        // 将原始数据转换为适合饼图数据的格式
        // this.projectTypeDataPie = Object.entries(this.projectTypeData).map(([key, value]) => ({
        //   name: key,
        //   value: value
        // }));

      })
      option && myChart.setOption(option);
    },
    procurementMethod() {
      const chartDom = document.getElementById('procurementMethod');
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center',
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['60%', '0%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'inner', // 标签位置
              formatter: '{d}%' // 使用百分比
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.procurementMethodDataPie // 使用组件的数据来定义饼图数据
          }
        ]
      };
      getPM().then(res => {
        this.procurementMethodData = res;
        this.procurementMethodDataPie = res;
        // 将对象转换为数组并格式化为适合 el-table 的数据格式
        this.procurementMethodCount = Object.entries(this.procurementMethodData).map(([key, value]) => ({
          procurementMethod: key,
          count: value
        }));

        option.series[0].data = [
          {name: "磋商", value: res["磋商"]},
          {name: "委托", value: res["委托"]},
          {name: "竞价", value: res["竞价"]},
        ]
        myChart.setOption(option);
      })
      option && myChart.setOption(option);
    },
    departmentProjects() {
      const chartDom = document.getElementById('sciproj');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '1%',
          right: '1%',
          bottom: '1%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0,1] // 设置柱状图宽度
        },
        yAxis: {
          type: 'category',
          data: []
        },
        series: [
          {
            name: '',
            type: 'bar',
            data: []
          }
        ]
      };
      //从后端获取纵坐标值与对应数据
      getSPBar().then(res => {
        option.yAxis.data = res.y; // 设置y轴值
        option.series[0].data = res.x; // 设置x轴数据
        option && myChart.setOption(option); //// 绘制图表
      }).catch(error => {
      })

    },
    async archiveTheProject() {
      const chartDom = document.getElementById('vertical-bar-chart');
      this.chart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: [],
          top: '10%',
          right: '10%',
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: [], // 日期数据
        },
        yAxis: {
          type: 'value',
        },
        series: [],
      };
      await getProjectsBySStatus(6).then(res => {
        this.projectData = res; // 存储原始数据
        this.filterData(); // 初始过滤数据并更新图表
        this.updateChartOptions(option); // 更新图表
      })
      this.chart.setOption(option);
    },

    // 过滤数据方法（需要根据需求进行自定义）
    filterData() {
      // 过滤项目数据（可以按时间范围或其他条件进行过滤）
      const currentDate = new Date();
      const filtered = this.projectData.filter(item => {
        const archiveDate = new Date(item.archiveTime);
        // 这里只是一个示例过滤条件，可以根据需求修改
        return archiveDate >= currentDate.setFullYear(currentDate.getFullYear() - 3); // 过滤出过去三年的数据
      });
      this.filteredData = filtered; // 更新过滤后的数据
    },

    // 更新图表选项
    updateChartOptions(option) {
      // 确保 option 和 option.series、option.xAxis 都已初始化
      if (!option) {
        console.error("Option is undefined");
        return;
      }

      if (!option.series) {
        console.error("Option.series is undefined, initializing it");
        option.series = [];
      }

      if (!option.xAxis) {
        console.error("Option.xAxis is undefined, initializing it");
        option.xAxis = { data: [] }; // 确保 xAxis.data 是一个空数组
      }

      // 对数据进行分组并计算每个日期的项目数量
      const groupedData = this.groupDataByDate(this.filteredData);
      const xAxisData = Object.keys(groupedData);

      // 动态提取所有年份
      const years = new Set();
      this.filteredData.forEach(item => {
        const year = new Date(item.archiveTime).getFullYear();
        years.add(year);
      });
      this.years = Array.from(years).sort((a, b) => a - b); // 排序年份

      // 动态生成 legend 和 series
      option.legend.data = this.years.map(year => `${year}`); // 图例数据
      option.series = []; // 清空原来的 series 数组

      this.years.forEach(year => {
        const seriesData = xAxisData.map(date => groupedData[date][year] || 0);
        option.series.push({
          name: `${year}`,
          type: 'bar',
          data: seriesData,
          itemStyle: {
            color: this.getColorForYear(year), // 动态设置颜色
          },
        });
      });

      option.xAxis.data = xAxisData;

      // 更新图表
      this.chart.setOption(option);
    },

    // 按日期对数据进行分组
    groupDataByDate(data) {
      const result = {};
      data.forEach(item => {
        const date = item.archiveTime.split('T')[0]; // 假设日期是 "yyyy-MM-dd" 格式
        const year = new Date(item.archiveTime).getFullYear(); // 提取年份
        if (!result[date]) {
          result[date] = {};
        }
        if (!result[date][year]) {
          result[date][year] = 0;
        }
        result[date][year]++; // 每个日期的每个年份对应的项目数加1
      });
      return result;
    },

    // 为每个年份生成不同的颜色
    getColorForYear(year) {
      const colors = {
        2021: '#73C9E6',
        2022: '#FF7F50',
        2023: '#FF6347',
        2024: '#FFD700',
        2025: '#32CD32',
      };
      return colors[year] || '#A9A9A9'; // 默认颜色
    },
  },

    // 按日期对数据进行分组
    groupDataByDate(data) {
      const result = {};
      data.forEach(item => {
        const date = item.archiveTime.split('T')[0]; // 假设日期是 "yyyy-MM-dd" 格式
        const year = new Date(item.archiveTime).getFullYear(); // 提取年份
        if (!result[date]) {
          result[date] = {};
        }
        if (!result[date][year]) {
          result[date][year] = 0;
        }
        result[date][year]++; // 每个日期的每个年份对应的项目数加1
      });
      return result;
    },

    // 为每个年份生成不同的颜色
    getColorForYear(year) {
      const colors = {
        2021: '#73C9E6',
        2022: '#FF7F50',
        2023: '#FF6347',
        2024: '#FFD700',
        2025: '#32CD32',
        2026: '#73C9E6',
        2027: '#FF7F50',
        2028: '#FF6347',
        2029: '#FFD700',
      };
      return colors[year] || '#A9A9A9'; // 默认颜色
     },
    beforeDestroy() {
      if (this.chart) {
        this.chart.dispose();
      }
    },
};
</script>

<style scoped>
.bar-chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>